"""
-*- coding: utf-8 -*-
@Author  : Link
@Time    : 2022/12/12 14:29
@Site    : 
@File    : app_variable.py
@Software: PyCharm
@Remark  : 
"""
import os
import time
from typing import Dict, Union, List

from BenchCore.variable_interface.app_project import AppProject
from BenchCore.bench_interface.limit_interface import Limit
from BenchCore.stdf_interface.stdf_create_interface import StdfSystem
from BenchCore.stdf_interface.stdf_def_interface import Mrr, Pir, Ptr, Prr, Mir, Wir, Sdr, Hbr, Sbr
from BenchCore.variable_interface.site_variable import SiteVariable
from BenchUtils.func import timestamp_to_str2
from BenchUtils.log_utils import Print


class AppVariable:
    """
    全局变量,所有的地方都可以使用到,主要是测试数据解析,存储和Limit
    """
    mir: Mir = None
    limit: Limit = None
    data_system: StdfSystem = None
    """
    BinSummary:
    HBin = {
        1: (1, "PASS", "P", 5),  # "BIN", "BIN_NAME", "BIN_TYPE", "BIN_QTY"
        2: (2, "OS", "F", 3),
    }

    SBin = {
        1: (1, "PASS", "P", 5),
        2: (2, "OS", "F", 3),
    }
    """
    hbr: Dict[int, list] = None
    sbr: Dict[int, list] = None
    file_name = None
    ready: bool = False

    def __init__(self, project: AppProject, curr_path: str):
        self.project = project

        Print.Info(" 初始化数据存储系统@ ")
        self.data_system = StdfSystem()
        self.hbr = dict()
        self.sbr = dict()

        Print.Info(" Limit读取@ ")
        self.limit = Limit()
        try:
            _, suffix = os.path.split(self.project.LIMIT_CSV_PATH)
            if suffix.split(".")[-1] == 'csv':
                self.limit.read_csv_data(os.path.join(curr_path, self.project.LIMIT_CSV_PATH))
            else:
                self.limit.read_tsv_data(os.path.join(curr_path, self.project.LIMIT_CSV_PATH))
        except Exception as err:
            Print.Danger("Limit数据读取失败,程序使用无Limit模式启动!:{}".format(err))

        self.ready = True

    def gen_temp_mir(self):
        setup_t = int(time.time())
        start_t = setup_t + 100
        self.mir = Mir(
            SETUP_T=setup_t,
            START_T=start_t,
            LOT_ID="TEMP",
            PART_TYP=self.project.PART_TYP,
            NODE_NAM="ATE",
            TSTR_TYP="Python",
            JOB_NAM=self.project.JOB_NAM,
            SBLOT_ID="TEMP",
            FLOW_ID="R0",
            TEST_COD=self.project.TEST_COD
        )

    def gen_mir(self, **kwargs):
        if kwargs.get("START_T", 0) == 0:
            setup_t = int(time.time())
            kwargs["SETUP_T"] = setup_t
            kwargs["START_T"] = setup_t + 100
        self.mir = Mir(
            **kwargs,
        )

    def gen_s_wir(self, **kwargs):
        if self.mir is None:
            return
        wir = Wir(**kwargs, START_T=self.mir.START_T)
        self.data_system.wir(wir)

    def lot_begin(self, dut: Union[int, List[int]] = 0):
        """
        生成mir
        更新数据存储器
        :return:
        """
        if self.mir is None:
            self.gen_temp_mir()
        self.file_name = os.path.join(self.project.STDF_SAVE_PATH,
                                      self.project.STDF_SAVE_NAME.format(**self.mir.to_dict(), DUT=dut))
        self.data_system.open("{}.stdtemp".format(self.file_name))
        self.data_system.far()
        self.data_system.atr("SAVE AS BY PYTHON STDF CONVERT")
        self.data_system.mir(self.mir)
        if isinstance(dut, int):
            dut = [dut]
        sdr = Sdr(SITE_NUM=dut)
        self.data_system.sdr(sdr)

    def lot_end(self, end_time: int = None):
        """
        如果是没有数据的就自动删除掉
        HBR? SBR? Summary? 生成格式还未确认
        :return:
        """
        if end_time is None:
            end_time = int(time.time())
        if self.data_system.f is None:
            return
        self.save_all_hbr()
        self.save_all_sbr()
        mrr = Mrr(FINISH_T=end_time)
        self.data_system.pcr()
        self.data_system.mrr(mrr)
        self.data_system.save()
        if not self.data_system.have_data:
            os.remove(self.data_system.save_path)
            return
        # ChangeName stdtemp -> stdf
        os.rename(self.data_system.save_path, self.file_name)

    def post_run(self, var: SiteVariable):
        """
        Todo: 在这里可以更新Summary
        """
        self.save_ptr(var)
        self.save_dtr(var)
        self.save_prr(var)

    def save_pir(self, site_var: SiteVariable):
        site_var.gen_pir()
        self.s_pir(site_var.pir)

    def save_ptr(self, site_var: SiteVariable):
        for ptr in site_var.ptr_list:
            self.s_ptr(ptr)

    def save_dtr(self, site_var: SiteVariable):
        for ptr in site_var.dtr_list:
            self.s_dtr(ptr)

    def save_prr(self, site_var: SiteVariable):
        self.s_prr(site_var.prr)
        Print.Record(site_var.prr.__str__())

    def save_all_hbr(self):
        for each in self.hbr.values():
            hbr = Hbr(
                SITE_NUM=0xff,
                HBIN_NUM=each[0],
                HBIN_CNT=each[3],
                HBIN_PF=each[2],
                HBIN_NAM=each[1],
            )
            self.data_system.hbr(hbr)

    def save_all_sbr(self):
        for each in self.sbr.values():
            sbr = Sbr(
                SITE_NUM=0xff,
                SBIN_NUM=each[0],
                SBIN_CNT=each[3],
                SBIN_PF=each[2],
                SBIN_NAM=each[1],
            )
            self.data_system.sbr(sbr)

    def save_hbr(self, site_var: SiteVariable):
        for each in site_var.hbr.values():
            hbr = Hbr(
                SITE_NUM=site_var.dut,
                HBIN_NUM=each[0],
                HBIN_CNT=each[3],
                HBIN_PF=each[2],
                HBIN_NAM=each[1],
            )
            self.data_system.hbr(hbr)

    def save_sbr(self, site_var: SiteVariable):
        for each in site_var.sbr.values():
            sbr = Sbr(
                SITE_NUM=site_var.dut,
                SBIN_NUM=each[0],
                SBIN_CNT=each[3],
                SBIN_PF=each[2],
                SBIN_NAM=each[1],
            )
            self.data_system.sbr(sbr)

    def print_bin(self):
        hbr, sbr = self.hbr, self.sbr
        keys = ["BIN", "BIN_NAME", "BIN_TYPE", "BIN_QTY"]
        summary = []
        all_qty = 0
        for key in sorted(hbr.keys()):
            temp = dict(zip(
                keys, hbr[key]
            ))
            summary.append(temp)
            all_qty += temp["BIN_QTY"]
        for each in summary:
            each["RATE"] = "%.2f%%" % (each["BIN_QTY"] / all_qty * 100)
        Print.PrintTable(summary)

    def s_wir(self, wir: Wir):
        self.data_system.wir(wir)

    def s_pir(self, pir: Pir):
        self.data_system.pir(pir)

    def s_ptr(self, ptr: Ptr):
        self.data_system.ptr(ptr)

    def s_dtr(self, dtr: str):
        self.data_system.log(dtr)

    def s_prr(self, prr: Prr):
        self.data_system.prr(prr)
